const expressions: ConditionExpressionMap = {
  '1': '!=',
  '2': '==',
  '3': '>',
  '4': '<',
  '5': 'includes',
  '6': 'not includes',
  '7': 'in',
  '8': 'not in',
};

const specialExpressions = {
  null: null,
  undefined: undefined,
  true: true,
  false: false,
};

const isObjOrArr = (str: string) => {
  if (!str) return false;
  return /^[\{|\[][\S|\s]*[\}\]]$/.test(str);
};

function formatCondition(item: { who: any; when: any; eq: any }): String {
  const { who, when, eq } = item;
  if (!who || !when) return 'true';

  let _item = `data.${who}`;
  let eqInput = eq;
  const expression = expressions[`${when}`];
  const speExpKes = Object.keys(specialExpressions);
  const isSpeInput = speExpKes.includes(`${eq}`);
  if (isSpeInput) eqInput = specialExpressions[`${eq}`];
  else if (isObjOrArr(eq)) eqInput = eq;
  else eqInput = `'${eq || ''}'`;

  if (when == 1 || when == 2) {
    return `${when == 1 ? '!' : ''}_.isEqual(${_item} || '', ${eqInput})`;
  }
  if (when == 3 || when == 4) {
    return `${_item} ${expression} ${eqInput || 0}`;
  }
  // 包含与不包含
  if (when == 5 || when == 6) {
    return `${when == 5 ? '' : '!'}_.includes(${_item}, ${eqInput})`;
  }
  // 被包含
  if (when == 7 || when == 8) {
    return `${when == 7 ? '' : '!'}_.includes(${eqInput}, ${_item})`;
  }
  return 'true';
}

function getContextComponents(context) {
  var values = [];
  context.utils.eachComponent(
    context.instance.options.editForm.components,
    function (component, path) {
      if (component.key !== context.data.key) {
        values.push({
          label: ''
            .concat(component.label || component.key, ' (')
            .concat(path, ')'),
          value: path,
        });
      }
    },
  );
  return values;
}

export default { formatCondition, getContextComponents };
